package com.czk.socket;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 三个核心：
 * 1 channel （SelectableChannel、SocketChannel ServerSocketChannel DatagramChannel）
 * 2 buffer 负责数据的存取
 * 3 selector 多路复用器，用于监控selectableChannel的IO状况
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/10 11:37
 */
public class BlockingNioTest {
    /**
     * 客户端
     *
     * @throws IOException
     */
    @Test
    public void client() throws IOException {
        // 创建网络传输channel
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        // 分配缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        /// 设置channel
        FileChannel open = FileChannel.open(Paths.get("D:\\简历\\罗琴.doc"), StandardOpenOption.READ);
        // 读取本地文件，发送到服务器
        while (open.read(byteBuffer) != -1) {
            byteBuffer.flip();
            socketChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        // 关闭通道
        open.close();
        socketChannel.close();
    }

    /**
     * 服务端
     *
     * @throws IOException
     */
    @Test
    public void server() throws IOException {
        // 获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9898));
        // 获取客户端的通道连接
        SocketChannel accept = serverSocketChannel.accept();
        // 接收客户端数据保存到本地
        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\简历\\1\\4.doc"), StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        // 分配指定大小的缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (accept.read(byteBuffer) != -1) {
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        // 关闭通道
        fileChannel.close();
        serverSocketChannel.close();
    }
}
